<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="100px">
      <el-form-item label="商品名称" prop="goodsName">
        <el-input v-model="queryParams.goodsName" placeholder="请输入商品名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="商品编码" prop="goodsNo">
        <el-input v-model="queryParams.goodsNo" placeholder="请输入商品编码" clearable style="width: 240px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 表格数据 -->
    <el-table v-loading="loading" :scrollbar-always-on="true" :data="groupList">
      <el-table-column label="图片" prop="goodsImageUrl" :show-overflow-tooltip="true" width="200">
        <template #default="scope">
          <el-image style="width: 100px; height: 100px" :src="scope.row.goodsImageUrl" fit="cover" />
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="goodsName" :show-overflow-tooltip="true" width="400"></el-table-column>
      <el-table-column label="编码" prop="goodsNo" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="款号" align="center" width="200" prop="fashionNo"> </el-table-column>
      <el-table-column label="片图" prop="goodsSliceImageUrl" :show-overflow-tooltip="true" width="200">
        <template #default="scope">
          <el-image style="width: 100px; height: 100px" :src="scope.row.goodsSliceImageUrl" fit="cover" />
        </template>
      </el-table-column>
      <el-table-column label="美工" prop="goodsArtDesigner" :show-overflow-tooltip="true" width="200"></el-table-column>
      <el-table-column label="库存" prop="goodsInventoryNum" align="center" width="100"></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="openDialog(scope.row)">唯一码</el-button>
          <el-button link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改商品配置对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="款式" prop="fashionId">
          <el-select v-model="form.fashionId" placeholder="请选择款式" clearable style="width: 200px">
            <el-option v-for="dict in TypeList" :key="dict.id" :label="dict.fashionName" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="form.goodsName" type="text" placeholder="请输入商品编码" />
        </el-form-item>
        <el-form-item label="商品编码" prop="goodsNo">
          <el-input v-model="form.goodsNo" placeholder="请输入商品编码" />
        </el-form-item>
        <el-form-item label="商品图片" prop="goodsImageUrl">
          <el-upload ref="uploadRef" style="width: 100%;" list-type="picture-card" v-model:file-list="fileList" :headers="headers" class="upload-demo"
            :action="actionUrl" :data="{ type: 0,  tenantGroupId: tenantGroupId  }" name="file" accept=".jpeg,.png" :on-error="handleUploadSuccess"
            :on-success="handleUploadSuccess" :on-exceed="handleExceed">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品素材" prop="goodsSourceMaterialUrl">
          <el-upload ref="uploadRef2" style="width: 100%;" list-type="picture-card" v-model:file-list="fileList2" :headers="headers" class="upload-demo"
            :action="actionUrl" :data="{ type: 0,  tenantGroupId: tenantGroupId  }" name="file" accept=".jpeg,.png" :on-error="handleUploadSuccess2"
            :on-success="handleUploadSuccess2" :on-exceed="handleExceed2">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品片图" prop="goodsSliceImageUrl">
          <el-upload ref="uploadRef3" style="width: 100%;" list-type="picture-card" v-model:file-list="fileList3" :headers="headers" class="upload-demo"
            :action="actionUrl" :limit="1" :data="{ type: 0,  tenantGroupId: tenantGroupId  }" name="file" accept=".jpeg,.png" :on-error="handleUploadSuccess3"
            :on-success="handleUploadSuccess3" :on-exceed="handleExceed3">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品唯一码" prop="goodsCodeUr">
          <el-upload ref="uploadRef4" style="width: 100%;" list-type="picture-card" v-model:file-list="fileList4" :headers="headers" class="upload-demo"
            :action="actionUrl" :limit="1" :data="{ type: 0,  tenantGroupId: tenantGroupId  }" name="file" accept=".jpeg,.png" :on-error="handleUploadSuccess4"
            :on-success="handleUploadSuccess4" :on-exceed="handleExceed4">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品价格" prop="goodsPrice">
          <el-input v-model="form.goodsPrice" placeholder="请输入商品价格" />
        </el-form-item>
        <el-form-item label="商品线色" prop="goodsLineColor">
          <el-input v-model="form.goodsLineColor" placeholder="请输入商品线色" />
        </el-form-item>
        <el-form-item label="美工人员" prop="goodsArtDesigner">
          <el-input v-model="form.goodsArtDesigner" placeholder="请输入美工" />
        </el-form-item>
        <el-form-item label="备注说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注说明" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="imgDialogVisible" width="900" title="唯一码">
      <img v-if="dialogImg" :src="dialogImg" />
      <el-empty description="暂无图片" v-else />
    </el-dialog>
  </div>
</template>

<script setup name="product">
  import { listType } from "@/api/order/type";
  import {
    list,
    add,
    edit,
    remove,
    styleList
  } from "@/api/order/product"
  import {
    listapplicant,
  } from "@/api/system/applicant";
  import baseForm from "../hooks/useOrderBase";
  const { headers, actionUrl, fileList, fileList2, fileList3, tenantGroupId } = baseForm();
  const router = useRouter();
  const route = useRoute()
  const { proxy } = getCurrentInstance();
  const imgDialogVisible = ref(false);
  const dialogImg = ref('')
  const TypeList = ref([])
  const groupList = ref([]);
  const open = ref(false);
  const appLicationList = ref([])
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref("");
  const dateRange = ref([]);
  const menuOptions = ref([]);
  const menuExpand = ref(false);
  const menuNodeAll = ref(false);
  const deptExpand = ref(true);
  const deptNodeAll = ref(false);
  const deptOptions = ref([]);
  const openDataScope = ref(false);
  const menuRef = ref(null);
  const deptRef = ref(null);
  const fileList4 = ref([])
  // 文件上传覆盖
  const uploadRef = ref();

  //弹窗 
  const openDialog = (row) => {
    dialogImg.value = row.goodsCodeUrl;
    imgDialogVisible.value = true
  }

  function handleExceed(files) {
    uploadRef.value.clearFiles();
    nextTick(() => {
      uploadRef.value.handleStart(files[0]);
      uploadRef.value.submit();
    });
  }
  const uploadRef2 = ref();

  function handleExceed2(files) {
    uploadRef2.value.clearFiles();
    nextTick(() => {
      uploadRef2.value.handleStart(files[0]);
      uploadRef2.value.submit();
    });
  }
  const uploadRef3 = ref();

  function handleExceed3(files) {
    uploadRef3.value.clearFiles();
    nextTick(() => {
      uploadRef3.value.handleStart(files[0]);
      uploadRef3.value.submit();
    });
  }
  const uploadRef4 = ref();

  function handleExceed4(files) {
    uploadRef4.value.clearFiles();
    nextTick(() => {
      uploadRef4.value.handleStart(files[0]);
      uploadRef4.value.submit();
    });
  }
  // 上传成功回调
  function handleUploadSuccess(res, file) {
    // 如果上传成功
    if (res.code == 200) {
      fileList.value = fileList.value.map((r) => { return r.response.data });
      form.value.goodsImageUrl = res.data.url;
    } else {
      proxy.$modal.msgError("上传失败:" + res.msg);
    }
  }
  // 上传成功回调
  function handleUploadSuccess2(res, file) {
    // 如果上传成功
    if (res.code == 200) {
      fileList2.value = fileList2.value.map((r) => { return r.response.data });
      form.value.goodsSourceMaterialUrl = fileList2.value.map((label) => {
        return label.url
      }).join(',');
    } else {
      proxy.$modal.msgError("上传失败:" + res.msg);
    }
  }
  // 上传成功回调
  function handleUploadSuccess3(res, file) {
    // 如果上传成功
    if (res.code == 200) {
      fileList3.value = fileList3.value.map((r) => { return r.response.data });
      form.value.goodsSliceImageUrl = fileList3.value.map((label) => {
        return label.url
      }).join(',');
    } else {
      proxy.$modal.msgError("上传失败:" + res.msg);
    }
  }
  // 上传成功回调
  function handleUploadSuccess4(res, file) {
    // 如果上传成功
    if (res.code == 200) {
      fileList4.value = fileList4.value.map((r) => { return r.response.data });
      form.value.goodsCodeUrl = fileList4.value.map((label) => {
        return label.url
      }).join(',');
    } else {
      proxy.$modal.msgError("上传失败:" + res.msg);
    }
  }
  /** 查询分类列表 */
  function getStyleList() {
    styleList({}).then(response => {
      TypeList.value = response.rows
    });
  }
  /** 查询应用列表 */
  function getAppLication() {
    listapplicant({ pageNum: 1, pageSize: 10000 }).then(response => {
      appLicationList.value = response.rows
    });
  }
  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      categoryId: null,
      fashionNo: undefined,
      fashionName: undefined
    },
    rules: {
      fashionId: [{ required: true, message: "款式不能为空", trigger: "blur" }],
      goodsName: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
      goodsNo: [{ required: true, message: "商品编码不能为空", trigger: "blur" }],
      goodsPrice: [{ required: true, message: "商品价格不能为空", trigger: "blur" }],
    },
  });
  const { queryParams, form, rules } = toRefs(data);
  /** 商品状态修改 */
  function handleStatusChange(row) {
    let text = row.styleAvl === "Y" ? "启用" : "禁用";
    proxy.$modal.confirm('确认要"' + text + '""' + row.styleName + '"用户组吗?').then(function() {
      return changeAvl({ id: row.id, styleAvl: row.styleAvl });
    }).then(() => {
      proxy.$modal.msgSuccess(text + "成功");
    }).catch(function() {
      row.styleAvl = row.styleAvl === "Y" ? "N" : "Y";
    });
  }
  /** 查询商品列表 */
  function getList() {
    loading.value = true;
    let formQueryParam = { ...queryParams.value };
    formQueryParam.expireTemp = formQueryParam.expireTemp == 0 ? '' : formQueryParam.expireTemp
    list(proxy.addDateRange(formQueryParam, dateRange.value)).then(response => {
      groupList.value = response.rows
      total.value = response.total;
      loading.value = false;
    });
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }
  /** 重置按钮操作 */
  function resetQuery() {
    dateRange.value = [];
    queryParams.value = {
      pageNum: 1,
      pageSize: 10,
      goodsName: '',
      goodsNo: ''
    }
    handleQuery();
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const ids = row.id || ids.value;
    proxy.$modal.confirm('是否确认删除商品编号为"' + ids + '"的数据项?').then(function() {
      return remove(ids);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download("system/role/export", {
      ...queryParams.value,
    }, `role_${new Date().getTime()}.xlsx`);
  }



  /** 重置新增的表单以及其他数据  */
  function reset() {
    if (menuRef.value != undefined) {
      menuRef.value.setCheckedKeys([]);
    }
    menuExpand.value = false;
    menuNodeAll.value = false;
    deptExpand.value = true;
    deptNodeAll.value = false;
    form.value = {

    };
    proxy.resetForm("roleRef");
  }

  /** 添加商品 */
  function handleAdd() {
    reset();
    open.value = true;
    fileList.value = [];
    fileList2.value = [];
    fileList3.value = [];
    fileList4.value = [];
    getStyleList()
    title.value = "添加商品";
  }

  /** 修改商品 */
  function handleUpdate(row) {
    reset();
    form.value = { ...row };
    fileList.value = form.value.goodsImageUrl ? form.value.goodsImageUrl.split(',').map((res) => {
      return { name: res, url: res }
    }) : [];
    fileList2.value = form.value.goodsSourceMaterialUrl ? form.value.goodsSourceMaterialUrl.split(',').map((res) => {
      return { name: res, url: res }
    }) : [];
    fileList3.value = form.value.goodsSliceImageUrl ? form.value.goodsSliceImageUrl.split(',').map((res) => {
      return { name: res, url: res }
    }) : [];
    fileList4.value = form.value.goodsCodeUrl ? form.value.goodsCodeUrl.split(',').map((res) => {
      return { name: res, url: res }
    }) : []
    open.value = true;
    title.value = "修改商品";
  }

  /** 提交按钮 */
  function submitForm() {
    let pass = true
    if (!form.value.id && form.value.tenantCreateParams && form.value.tenantCreateParams.length) {
      form.value.tenantCreateParams.forEach((a, index) => {
        if (!a.applicantId || !a.tenantCode || !a.tenantName) {
          pass = false
        }
      })
    }
    if (!pass) {
      proxy.$modal.msgWarning("商品列表下内容不能有空~");
      return
    }
    // if (form.value.styleExpireStatus == 'T' && !form.value.styleExpireDate) {
    //   proxy.$modal.msgWarning("请选择截止日期~");
    //   return
    // }
    proxy.$refs["roleRef"].validate(valid => {
      if (valid) {
        if (form.value.id != undefined) {
          edit(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          add(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  /** 取消按钮 */
  function cancel() {
    open.value = false;
    reset();
  }
  getList();
  getStyleList()
</script>